package com.chucang.shucang.auth.support.sms;

import cn.hutool.extra.spring.SpringUtil;
import com.chucang.shucang.auth.support.base.OAuth2ResourceOwnerBaseAuthenticationConverter;
import com.chucang.shucang.common.base.constant.CacheConstant;
import com.chucang.shucang.common.base.constant.SecurityConstant;
import com.chucang.shucang.common.base.redis.RedisUtil;
import com.chucang.shucang.common.security.utils.OAuth2EndpointUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/9/15 21:16
 * @description 短信登录转换
 */
@Slf4j
public class OAuth2ResourceOwnerSmsAuthenticationConverter extends OAuth2ResourceOwnerBaseAuthenticationConverter<OAuth2ResourceOwnerSmsAuthenticationToken> {

    /**
     * 是否支持此convert
     *
     * @param grantType 授权类型
     * @return b
     */
    @Override
    public boolean support(String grantType) {
        return SecurityConstant.APP.equals(grantType);
    }

    @Override
    public OAuth2ResourceOwnerSmsAuthenticationToken buildToken(Authentication clientPrincipal, Set<String> requestedScopes,
                                                                Map<String, Object> additionalParameters) {
        return new OAuth2ResourceOwnerSmsAuthenticationToken(new AuthorizationGrantType(SecurityConstant.APP),
                clientPrincipal, requestedScopes, additionalParameters);
    }

    /**
     * 校验扩展参数 密码模式密码必须不为空
     *
     * @param request 参数列表
     */
    @Override
    public void checkParams(HttpServletRequest request) {
        MultiValueMap<String, String> parameters = OAuth2EndpointUtil.getParameters(request);
        // PHONE (REQUIRED)
        String phone = parameters.getFirst(SecurityConstant.SMS_PARAMETER_NAME);
        String smsCode = parameters.getFirst(SecurityConstant.SMS_CODE);
        if (!StringUtils.hasText(phone) || parameters.get(SecurityConstant.SMS_PARAMETER_NAME).size() != 1) {
            OAuth2EndpointUtil.throwError(OAuth2ErrorCodes.INVALID_REQUEST, SecurityConstant.SMS_PARAMETER_NAME,
                    OAuth2EndpointUtil.ACCESS_TOKEN_REQUEST_ERROR_URI);
        }
        if (!StringUtils.hasText(smsCode) || parameters.get(SecurityConstant.SMS_CODE).size() != 1) {
            OAuth2EndpointUtil.throwError(OAuth2ErrorCodes.INVALID_REQUEST, SecurityConstant.SMS_CODE,
                    OAuth2EndpointUtil.ACCESS_TOKEN_REQUEST_ERROR_URI);
        }
        //校验验证码
        String format = String.format(CacheConstant.USER_LOGIN_SMS_CODE, phone);
        log.info("开始校验验证码，key为{},需要验证的验证码为{}", format, smsCode);
        RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
        Object code = redisUtil.getObject(format);
        Optional.ofNullable(code)
                .ifPresentOrElse(c -> {
                            if (!c.toString().equals(smsCode)) {
                                OAuth2EndpointUtil.throwError("短信验证码验证失败", SecurityConstant.SMS_CODE,
                                        OAuth2EndpointUtil.ACCESS_TOKEN_REQUEST_ERROR_URI);
                            }
                        }, () ->
                                OAuth2EndpointUtil.throwError(OAuth2ErrorCodes.INVALID_REQUEST, SecurityConstant.SMS_CODE,
                                        OAuth2EndpointUtil.ACCESS_TOKEN_REQUEST_ERROR_URI)
                );
    }
}
